/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.bsly.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.bsly.common.utils.JwtUtils;
import io.bsly.common.utils.R;
import io.bsly.modules.app.annotation.JwtIgnore;
import io.bsly.modules.sys.entity.SysUserEntity;
import io.bsly.modules.sys.pojo.SysLoginForm;
import io.bsly.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 登录相关
 *
 * @author Mark sunlightcs@gmail.com
 */
@Api(tags = "后台登录")
@RestController
@RequestMapping("/sys")
public class SysLoginController  {
	@Autowired
	private SysUserService sysUserService;

	@Autowired
	RedisTemplate redisTemplate;

	@Autowired
	private JwtUtils jwtUtils;

	/**
	 * 登录
	 */
	@ApiOperation(value = "登录")
	@JwtIgnore
	@PostMapping("/login")
	public Map<String, Object> login(@RequestBody SysLoginForm form){
		//用户信息
		SysUserEntity sysUserEntity = sysUserService.getOne(new QueryWrapper<SysUserEntity>().lambda().eq(SysUserEntity::getUsername,form.getUsername()));
		String userPass = DigestUtils.sha256Hex(form.getPassword());
		//账号不存在、密码错误
		if(sysUserEntity == null || !userPass.equals(sysUserEntity.getPassword())) {
			return R.error("账号或密码不正确");
		}
		//账号锁定
		if(sysUserEntity.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}
		String token = jwtUtils.generateToken(sysUserEntity.getId());
		return R.ok().put("token",token);
	}


}
